package com.store.app.activity;

import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.store.app.BaseActivity;
import com.store.app.R;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.PayBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.pay.alipay.Alipay;
import com.store.app.pay.alipay.AlipayModel;
import com.store.app.pay.alipay.AlipayState;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.wxapi.WXOrderbean;
import com.store.app.wxapi.WetchatPay;

import org.json.JSONException;
import org.json.JSONObject;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/12/26.
 * 充值中心
 */
public class RechargePayActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener, AlipayState {
    private TextView tv_pay_number;     //充值号码
    private TextView tv_pay_money;      //充值金额
    private TextView tv_tip;            //充值提示
    private RadioButton rad1;           //零钱
    private RadioButton rad2;           //支付宝
    private RadioButton rad3;           //微信支付
    private RadioGroup radioGroup;
    private Button bt_pay;             //立即充值
    private String jsonInfo;          //上个页面传过来的（js）
    private String mobile = "";
    private String title = "";
    private String discount_price = "0.00";
    private String goods_id = "";
    private String market_price = "0.00";
    private int FLag = 1;//默认钱包支付
    private NetRequest netRequest;
    private ImageView public_ll_return;
    private TextView tvTitle;
    private TextView tv_usable_money;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_pay);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        jsonInfo = getIntent().getStringExtra("jsonInfo");
        try {
            JSONObject jsonObject = new JSONObject(jsonInfo);
            mobile = jsonObject.getString("mobile");
            title = jsonObject.getString("title");
            discount_price = jsonObject.getString("discount_price");
            goods_id = jsonObject.getString("goods_id");
            market_price = jsonObject.getString("market_price");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tv_pay_number.setText("为" + mobile + "充值");
        tv_pay_money.setText(market_price);
        bt_pay.setText("确认支付 ¥" + discount_price);
        String str = "请在提交订单后<font color='#ffb142'>30分钟</font>内完成支付，否则系统将会自动取消订单";
        tv_tip.setText(Html.fromHtml(str));
        netRequest = new NetRequest(this);
        tvTitle.setText("充值中心");
        netRequest.requestUsableCashBalanceFind(2);
    }

    private void initView() {
        tv_pay_number = (TextView) findViewById(R.id.tv_pay_number);
        tv_pay_money = (TextView) findViewById(R.id.tv_pay_money);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        rad1 = (RadioButton) findViewById(R.id.rad1);
        rad2 = (RadioButton) findViewById(R.id.rad2);
        rad3 = (RadioButton) findViewById(R.id.rad3);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        bt_pay = (Button) findViewById(R.id.bt_pay);
        bt_pay.setOnClickListener(this);
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rad1://每天惠钱包
                        rest(rad1);
                        FLag = 1;
                        break;
                    case R.id.rad2://支付宝
                        rest(rad2);
                        FLag = 2;
                        break;
                    case R.id.rad3://微信支付
                        rest(rad3);
                        FLag = 3;
                        break;

                }
            }
        });
        tv_usable_money = (TextView) findViewById(R.id.tv_usable_money);
    }

    void rest(RadioButton radioButton) {
        Resources res = getResources();
        Drawable draw_pressed = res.getDrawable(R.drawable.check_pressed);
        Drawable draw_norml = res.getDrawable(R.drawable.check_normal);
        if (radioButton == rad1) {
            rad1.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_pressed, null);
            rad2.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_norml, null);
            rad3.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_norml, null);
        } else if (radioButton == rad2) {
            rad1.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_norml, null);
            rad2.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_pressed, null);
            rad3.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_norml, null);
        } else if (radioButton == rad3) {
            rad1.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_norml, null);
            rad2.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_norml, null);
            rad3.setCompoundDrawablesWithIntrinsicBounds(null, null, draw_pressed, null);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_pay:
                if (Utils.isFastClick()) {
                    return;
                }
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(RechargePayActivity.this);
                String login_phone = preferences.getString("login_phone", "");
                //零钱充值
                if (FLag == 1) {
                    netRequest.requestMobileRechargePay(1, mobile, login_phone, login_phone, goods_id, SettingData.PAYMENT_WAY_05);
                }
                //支付宝
                else if (FLag == 2) {
                    netRequest.requestMobileRechargePay(3, mobile, login_phone, login_phone, goods_id, SettingData.PAYMENT_WAY_01);
                }
                //微信
                else if (FLag == 3) {
                    netRequest.requestMobileRechargePay(4, mobile, login_phone, login_phone, goods_id, SettingData.PAYMENT_WAY_02);
                }
                break;
            case R.id.public_ll_return:
                finish();
                break;
        }
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //零钱充值成功
        if (requestId == 1) {
            netRequest.requestUsableCashBalanceFind(2);
            EventBus.getDefault().post(new EventBusBean(220));
            showToast("支付成功");
            finish();
        }
        //查询资产信息成功
        else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String usable_cash_balance = jsonObject.getString("usable_cash_balance");
                Log.v("zyl", "设置可用金额：" + usable_cash_balance);
                tv_usable_money.setText(usable_cash_balance+"元");
            } catch (Exception e) {
            }
        }
        //支付宝支付成功（接口调用成功）
        else if (requestId == 3) {
            AlipayModel model = new AlipayModel();
            model.json2Model(result);
            new Alipay(RechargePayActivity.this, model, RechargePayActivity.this).pay();
        }
        //微信支付成功（接口调用成功）
        else if (requestId == 4) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                WXOrderbean wxOrderbean = new WXOrderbean();
                wxOrderbean.setTransaction_no(jsonObject.getString("transaction_no"));
                wxOrderbean.setTimestamp(jsonObject.getString("timestamp"));
                wxOrderbean.setSign(jsonObject.getString("sign"));
                wxOrderbean.setPartnerid(jsonObject.getString("partnerid"));
                wxOrderbean.setPackageX(jsonObject.getString("package"));
                wxOrderbean.setNoncestr(jsonObject.getString("noncestr"));
                wxOrderbean.setAppid(jsonObject.getString("appid"));
                wxOrderbean.setPrepayid(jsonObject.getString("prepayid"));
                WetchatPay wetchatPay = new WetchatPay(RechargePayActivity.this, wxOrderbean);
                wetchatPay.pay();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void onEvent(PayBean busBean) {
        //微信支付成功
        if (busBean.type == 2) {
            Log.v("zyl", "微信支付成功");
            showToast("支付成功");
            EventBus.getDefault().post(new EventBusBean(220));
            finish();
        } else if (busBean.type == -2) {
            Log.v("zyl", "微信取消");
        } else if (busBean.type == -1) {
            Log.v("zyl", "微信取消");
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showToast(msg);
    }

    @Override
    public void onAlipaySuccess() {
        showToast("支付成功");
        EventBus.getDefault().post(new EventBusBean(220));
        finish();
    }

    @Override
    public void onAlipayFail() {
    }
}
